package com.ahaoyou.excel;

import cn.hutool.core.collection.CollectionUtil;
import com.ahaoyou.entity.User;
import com.ahaoyou.mapper.UserMapper;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @Author LH
 * @create 2021/12/31 10:47
 * 监听读取
 */
@Slf4j
public class ExcelDataListener extends AnalysisEventListener<User> {

    private static final int BATCH_COUNT = 10;

    private List<User> list = CollectionUtil.newArrayList();

    private UserMapper userMapper;

    public ExcelDataListener(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public void invoke(User user, AnalysisContext analysisContext) {
        log.info("读取到信息:{}", user);
        if (user != null) {
            list.add(user);
        }
        if (list.size() >= BATCH_COUNT) {
            userMapper.saveUser(list);
            log.info("添加数据成功");
            // 存储完成清理 list
            list.clear();
        }
    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        userMapper.saveUser(list);
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        super.onException(exception, context);
        log.info("解析失败:{}", exception.getMessage());
    }
}
